package seo.dale.util.time;

import java.util.Calendar;
import java.util.Date;

import org.joda.time.DateTime;
import org.joda.time.Days;
import org.joda.time.LocalDate;
import org.joda.time.Years;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;

public class DateTimeUtils {
	
	/**
	 * Used when you send the timestamp calling an Open API. 
	 * @return rounded timestamp in sec
	 */
	public static long getCurrentTimestamp() {
		return Math.round(System.currentTimeMillis() / 1000.0);
	}
	
	public static Date getPastSunday(Date date) {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		calendar.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY); // Sunday is 1.
		return calendar.getTime();
	}
	
	public static Date getComingSunday(Date date) {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		calendar.add(Calendar.WEEK_OF_MONTH, 1); // Next week
		calendar.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY); // Sunday is 1.
		return calendar.getTime();
	}
	
	public static boolean isWithinPastWeek(Date date) {
		Calendar calendar = Calendar.getInstance();
		calendar.set(Calendar.HOUR_OF_DAY, 0);
		calendar.set(Calendar.MINUTE, 0);
		calendar.set(Calendar.SECOND, 0);
		calendar.set(Calendar.MILLISECOND, 0);
		long millisecondsBetween = calendar.getTimeInMillis() - date.getTime();
		long daysBetween = millisecondsBetween / (1000 * 60 * 60 * 24);
		
		if (daysBetween >= 0 && daysBetween <= 7) {
			return true;
		} else {
			return false;
		}
	}
	
	public static boolean isWithinPastWeek2(Date date) {
		LocalDate currentDate = new LocalDate();
		LocalDate givenDate = new LocalDate(date);
		
		int daysBetween = Days.daysBetween(givenDate, currentDate).getDays();
		if (daysBetween >= 0 && daysBetween <= 7) {
			return true;
		} else {
			return false;
		}
	}
	
	public static boolean isNowBetween(Date startDate, Date endDate) {
		DateTime startDateTime = new DateTime(startDate);
		DateTime endDateTime = new DateTime(endDate);
		return startDateTime.isBeforeNow() && endDateTime.isAfterNow();
	}
	
	public static int getAge(String yyyyMMdd) {
		LocalDate birthDay;
		try {
			DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyyMMdd");
			birthDay = LocalDate.parse(yyyyMMdd, formatter);
		} catch (IllegalArgumentException e) {
			return -1;
		}
		
		LocalDate today = LocalDate.now();
		Years years = Years.yearsBetween(birthDay, today);
		return years.getYears();
	}
	
}
